<template>
  <div class="batch-trace-result">
    <!-- 批次基本信息 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="batch-card">
          <div slot="header" class="card-header">
            <span>批次基本信息</span>
            <el-button type="primary" size="small" @click="exportData">
              <i class="el-icon-download"></i> 导出批次记录
            </el-button>
          </div>
          <el-descriptions :column="4" border>
            <el-descriptions-item label="批次编号">{{ traceData.batch?.batchNo || '--' }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{ traceData.batch?.productName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="产品编号">{{ traceData.batch?.productCode || '--' }}</el-descriptions-item>
            <el-descriptions-item label="计划数量">{{ traceData.batch?.planQuantity || '--' }}</el-descriptions-item>
            <el-descriptions-item label="实际数量">{{ traceData.batch?.actualQuantity || '--' }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ traceData.batch?.startTime || '--' }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">{{ traceData.batch?.endTime || '--' }}</el-descriptions-item>
            <el-descriptions-item label="批次状态">
              <el-tag :type="getBatchStatusType(traceData.batch?.status)">
                {{ getBatchStatusText(traceData.batch?.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 质量统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>质量统计</span>
          </div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8">
              <div class="stats-item">
                <div class="item-title">合格率</div>
                <div class="item-value" :class="getQualificationRateClass(traceData.stats?.qualificationRate)">
                  {{ formatPercentage(traceData.stats?.qualificationRate) }}
                </div>
                <div class="item-desc">完成检验: {{ traceData.stats?.inspectedQuantity || 0 }} / 合格: {{ traceData.stats?.qualifiedQuantity || 0 }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <div class="stats-item">
                <div class="item-title">一次通过率</div>
                <div class="item-value" :class="getQualificationRateClass(traceData.stats?.firstPassRate)">
                  {{ formatPercentage(traceData.stats?.firstPassRate) }}
                </div>
                <div class="item-desc">首次合格: {{ traceData.stats?.firstPassQuantity || 0 }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <div class="stats-item">
                <div class="item-title">缺陷密度</div>
                <div class="item-value" :class="getDefectDensityClass(traceData.stats?.defectDensity)">
                  {{ traceData.stats?.defectDensity || 0 }}
                </div>
                <div class="item-desc">缺陷数: {{ traceData.stats?.defectCount || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 工序进度 -->
    <el-row :gutter="20" class="process-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>工序进度</span>
          </div>
          <el-steps :active="getActiveProcessIndex()" finish-status="success" align-center>
            <el-step 
              v-for="(process, index) in traceData.processes" 
              :key="index" 
              :title="process.processName"
              :description="getProcessDescription(process)">
            </el-step>
          </el-steps>
          <div class="chart-container" ref="processChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 检验记录 -->
    <el-row :gutter="20" class="inspection-row">
      <el-col :span="24">
        <el-card shadow="hover" class="inspection-card">
          <div slot="header" class="card-header">
            <span>检验记录</span>
          </div>
          <el-tabs v-model="activeInspectionTab">
            <el-tab-pane label="首检" name="first">
              <el-table :data="getInspectionsByType('first')" stripe>
                <el-table-column prop="inspectionNo" label="检验单号"></el-table-column>
                <el-table-column prop="inspectionTime" label="检验时间"></el-table-column>
                <el-table-column prop="inspector" label="检验员"></el-table-column>
                <el-table-column label="结果">
                  <template v-slot="scope">
                    <el-tag v-if="scope && scope.row" :type="getInspectionResultType(scope.row.result)">
                      {{ getInspectionResultText(scope.row.result) }}
                    </el-tag>
                    <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="itemsCount" label="检验项数"></el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                  <template v-slot="scope">
                    <el-button
                      v-if="scope && scope.row"
                      @click.native.prevent="viewInspectionDetails(scope.row)"
                      link
                      size="small">
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="巡检" name="patrol">
              <el-table :data="getInspectionsByType('patrol')" stripe>
                <el-table-column prop="inspectionNo" label="检验单号"></el-table-column>
                <el-table-column prop="inspectionTime" label="检验时间"></el-table-column>
                <el-table-column prop="inspector" label="检验员"></el-table-column>
                <el-table-column label="结果">
                  <template v-slot="scope">
                    <el-tag v-if="scope && scope.row" :type="getInspectionResultType(scope.row.result)">
                      {{ getInspectionResultText(scope.row.result) }}
                    </el-tag>
                    <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="itemsCount" label="检验项数"></el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                  <template v-slot="scope">
                    <el-button
                      v-if="scope && scope.row"
                      @click.native.prevent="viewInspectionDetails(scope.row)"
                      link
                      size="small">
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="终检" name="final">
              <el-table :data="getInspectionsByType('final')" stripe>
                <el-table-column prop="inspectionNo" label="检验单号"></el-table-column>
                <el-table-column prop="inspectionTime" label="检验时间"></el-table-column>
                <el-table-column prop="inspector" label="检验员"></el-table-column>
                <el-table-column label="结果">
                  <template v-slot="scope">
                    <el-tag v-if="scope && scope.row" :type="getInspectionResultType(scope.row.result)">
                      {{ getInspectionResultText(scope.row.result) }}
                    </el-tag>
                    <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="itemsCount" label="检验项数"></el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                  <template v-slot="scope">
                    <el-button
                      v-if="scope && scope.row"
                      @click.native.prevent="viewInspectionDetails(scope.row)"
                      link
                      size="small">
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 异常记录 -->
    <el-row :gutter="20" class="defect-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>异常记录</span>
          </div>
          <el-table :data="traceData.defects || []" stripe>
            <el-table-column prop="defectCode" label="缺陷编号"></el-table-column>
            <el-table-column prop="defectName" label="缺陷类型"></el-table-column>
            <el-table-column prop="processName" label="发生工序"></el-table-column>
            <el-table-column prop="findTime" label="发现时间"></el-table-column>
            <el-table-column label="严重程度">
              <template v-slot="scope">
                <el-tag v-if="scope && scope.row" :type="getDefectSeverityType(scope.row.severity)">
                  {{ scope.row.severity || '未知' }}
                </el-tag>
                <span v-else>未知</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template v-slot="scope">
                <el-tag v-if="scope && scope.row" :type="getDefectStatusType(scope.row.status)">
                  {{ getDefectStatusText(scope.row.status) }}
                </el-tag>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template v-slot="scope">
                <el-button
                  v-if="scope && scope.row"
                  @click.native.prevent="viewDefectDetails(scope.row)"
                  link
                  size="small">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!traceData.defects || traceData.defects.length === 0" class="empty-data">
            <el-empty description="无异常记录"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 影响范围评估 -->
    <el-row :gutter="20" class="impact-row" v-if="traceData.impactAssessment">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>影响范围评估</span>
          </div>
          <el-tabs v-model="activeImpactTab">
            <el-tab-pane label="相关批次" name="batches">
              <el-table :data="traceData.impactAssessment.relatedBatches || []" stripe>
                <el-table-column prop="batchNo" label="批次号"></el-table-column>
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <el-table-column prop="relation" label="关联类型"></el-table-column>
                <el-table-column prop="startTime" label="生产时间"></el-table-column>
                <el-table-column prop="status" label="状态">
                  <template slot-scope="scope">
                    <el-tag :type="getBatchStatusType(scope.row?.status)">
                      {{ getBatchStatusText(scope.row?.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="viewBatchDetails(scope.row)"
                      link
                      size="small">
                      查看批次
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="!traceData.impactAssessment.relatedBatches || traceData.impactAssessment.relatedBatches.length === 0" class="empty-data">
                <el-empty description="无相关批次"></el-empty>
              </div>
            </el-tab-pane>
            <el-tab-pane label="相关工艺" name="processes">
              <el-table :data="traceData.impactAssessment.relatedProcesses || []" stripe>
                <el-table-column prop="processName" label="工艺名称"></el-table-column>
                <el-table-column prop="processCode" label="工艺编号"></el-table-column>
                <el-table-column prop="relation" label="关联类型"></el-table-column>
                <el-table-column prop="impactLevel" label="影响程度">
                  <template slot-scope="scope">
                    <el-tag :type="getImpactLevelType(scope.row.impactLevel)">
                      {{ scope.row.impactLevel }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="recommendation" label="建议"></el-table-column>
              </el-table>
              <div v-if="!traceData.impactAssessment.relatedProcesses || traceData.impactAssessment.relatedProcesses.length === 0" class="empty-data">
                <el-empty description="无相关工艺"></el-empty>
              </div>
            </el-tab-pane>
            <el-tab-pane label="潜在风险" name="risks">
              <el-table :data="traceData.impactAssessment.potentialRisks || []" stripe>
                <el-table-column prop="riskName" label="风险名称"></el-table-column>
                <el-table-column prop="category" label="风险类别"></el-table-column>
                <el-table-column prop="probability" label="发生概率"></el-table-column>
                <el-table-column prop="severity" label="严重程度">
                  <template slot-scope="scope">
                    <el-tag :type="getRiskSeverityType(scope.row.severity)">
                      {{ scope.row.severity }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="mitigation" label="缓解措施"></el-table-column>
              </el-table>
              <div v-if="!traceData.impactAssessment.potentialRisks || traceData.impactAssessment.potentialRisks.length === 0" class="empty-data">
                <el-empty description="无潜在风险"></el-empty>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详情对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <div v-loading="dialogLoading">
        <component :is="currentDetailComponent" :data="detailData"></component>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { exportBatchTrace } from "@/api/qep/dataAnalysis";

export default {
  name: "BatchTraceResult",
  props: {
    traceData: {
      type: Object,
      required: true
    },
    batchNo: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      qualityChart: null,
      processChart: null,
      activeInspectionTab: 'first',
      activeImpactTab: 'batches',
      dialogVisible: false,
      dialogTitle: '',
      dialogLoading: false,
      currentDetailComponent: null,
      detailData: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      try {
        if (this.traceData && this.traceData.processStats && this.traceData.processStats.length > 0) {
          this.initProcessChart();
        }
        window.addEventListener('resize', this.resizeCharts);
      } catch (error) {
        console.error('Error initializing charts:', error);
      }
    });
  },
  beforeDestroy() {
    try {
      if (this.processChart) {
        this.processChart.dispose();
        this.processChart = null;
      }
      window.removeEventListener('resize', this.resizeCharts);
    } catch (error) {
      console.error('Error disposing charts:', error);
    }
  },
  methods: {
    // 初始化图表
    initQualityChart() {
      if (!this.$refs.qualityChart) return;
      
      try {
        // 检查是否已经初始化过
        if (this.qualityChart) {
          this.qualityChart.dispose();
        }
        
        this.qualityChart = echarts.init(this.$refs.qualityChart);
        
        // 检查数据是否存在
        const stats = this.traceData.stats || {};
        if (stats === null || typeof stats !== 'object') {
          this.qualityChart.setOption({
            title: {
              text: '暂无质量数据',
              left: 'center',
              top: 'center',
              textStyle: { color: '#888' }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
          return;
        }
        
        // 准备数据
        const qualifiedRate = parseFloat(stats.qualificationRate) || 0;
        const defectRate = parseFloat(stats.defectRate) || 0;
        const pendingRate = Math.max(0, 100 - qualifiedRate - defectRate);
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'horizontal',
            bottom: 0,
            data: ['合格', '不合格', '待检']
          },
          series: [
            {
              name: '批次质量',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: qualifiedRate, name: '合格', itemStyle: { color: '#67C23A' } },
                { value: defectRate, name: '不合格', itemStyle: { color: '#F56C6C' } },
                { value: pendingRate, name: '待检', itemStyle: { color: '#E6A23C' } }
              ]
            }
          ]
        };
        
        this.qualityChart.setOption(option);
      } catch (error) {
        console.error('Failed to initialize quality chart:', error);
      }
    },
    
    initProcessChart() {
      if (!this.$refs.processChart) return;
      
      try {
        // 检查数据是否存在
        if (!this.traceData.processStats || !Array.isArray(this.traceData.processStats) || this.traceData.processStats.length === 0) {
          // 检查是否已经初始化过
          if (this.processChart) {
            this.processChart.dispose();
          }
          
          this.processChart = echarts.init(this.$refs.processChart);
          this.processChart.setOption({
            title: {
              text: '暂无工序数据',
              left: 'center',
              top: 'center',
              textStyle: { color: '#888' }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
          return;
        }
        
        // 检查是否已经初始化过
        if (this.processChart) {
          this.processChart.dispose();
        }
        
        this.processChart = echarts.init(this.$refs.processChart);
        
        const processNames = this.traceData.processStats.map(item => item.processName || '未知工序');
        const qualifiedRates = this.traceData.processStats.map(item => parseFloat(item.qualifiedRate) || 0);
        const productionRates = this.traceData.processStats.map(item => parseFloat(item.productionRate) || 0);
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['合格率', '生产进度']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01],
            axisLabel: {
              formatter: '{value}%'
            },
            max: 100
          },
          yAxis: {
            type: 'category',
            data: processNames
          },
          series: [
            {
              name: '合格率',
              type: 'bar',
              data: qualifiedRates,
              itemStyle: {
                color: '#67C23A'
              }
            },
            {
              name: '生产进度',
              type: 'bar',
              data: productionRates,
              itemStyle: {
                color: '#409EFF'
              }
            }
          ]
        };
        
        this.processChart.setOption(option);
      } catch (error) {
        console.error('Failed to initialize process chart:', error);
      }
    },
    
    resizeCharts() {
      try {
        if (this.qualityChart && this.$refs.qualityChart && this.qualityChart.resize) {
          this.qualityChart.resize();
        }
        
        if (this.processChart && this.$refs.processChart && this.processChart.resize) {
          this.processChart.resize();
        }
      } catch (error) {
        console.error('Error resizing charts:', error);
      }
    },
    
    // 格式化百分比
    formatPercentage(value) {
      if (value === undefined || value === null) return '0%';
      return (parseFloat(value) || 0).toFixed(2) + '%';
    },
    
    // 获取活动工序索引
    getActiveProcessIndex() {
      if (!this.traceData?.processes) return 0;
      
      const index = this.traceData.processes.findIndex(process => 
        process.status === 'processing' || process.status === 'pending');
      
      return index === -1 ? this.traceData.processes.length : index;
    },
    
    // 获取工序描述
    getProcessDescription(process) {
      if (!process) return '';
      
      if (process.status === 'completed') {
        return `已完成 (${process.endTime || ''})`;
      } else if (process.status === 'processing') {
        return '进行中';
      } else if (process.status === 'pending') {
        return '待开始';
      } else {
        return process.status || '未知';
      }
    },
    
    // 按类型过滤检验记录
    getInspectionsByType(type) {
      if (!this.traceData?.inspections) return [];
      return this.traceData.inspections.filter(item => item.inspectionType === type);
    },
    
    // 批次状态
    getBatchStatusType(status) {
      const statusMap = {
        'planning': 'info',
        'in_production': 'warning',
        'completed': 'success',
        'on_hold': 'danger',
        'canceled': 'info'
      };
      return statusMap[status] || 'info';
    },
    getBatchStatusText(status) {
      const statusMap = {
        'planning': '计划中',
        'in_production': '生产中',
        'completed': '已完成',
        'on_hold': '挂起',
        'canceled': '已取消'
      };
      return statusMap[status] || '未知';
    },
    
    // 合格率样式
    getQualificationRateClass(rate) {
      if (rate === undefined || rate === null) return '';
      if (rate >= 99) return 'text-excellent';
      if (rate >= 95) return 'text-good';
      if (rate >= 90) return 'text-adequate';
      return 'text-poor';
    },
    
    // 缺陷密度样式
    getDefectDensityClass(density) {
      if (density === undefined || density === null) return '';
      if (density <= 0.5) return 'text-excellent';
      if (density <= 1) return 'text-good';
      if (density <= 2) return 'text-adequate';
      return 'text-poor';
    },
    
    // 检验结果
    getInspectionResultType(result) {
      const resultMap = {
        'pass': 'success',
        'fail': 'danger',
        'conditional_pass': 'warning'
      };
      return resultMap[result] || 'info';
    },
    getInspectionResultText(result) {
      const resultMap = {
        'pass': '合格',
        'fail': '不合格',
        'conditional_pass': '有条件通过'
      };
      return resultMap[result] || '未知';
    },
    
    // 缺陷严重程度
    getDefectSeverityType(severity) {
      const severityMap = {
        '严重': 'danger',
        '中等': 'warning',
        '轻微': 'info'
      };
      return severityMap[severity] || 'info';
    },
    
    // 缺陷状态
    getDefectStatusType(status) {
      const statusMap = {
        'open': 'danger',
        'in_progress': 'warning',
        'resolved': 'success',
        'closed': 'info'
      };
      return statusMap[status] || 'info';
    },
    getDefectStatusText(status) {
      const statusMap = {
        'open': '未处理',
        'in_progress': '处理中',
        'resolved': '已解决',
        'closed': '已关闭'
      };
      return statusMap[status] || '未知';
    },
    
    // 影响程度
    getImpactLevelType(level) {
      const levelMap = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      };
      return levelMap[level] || 'info';
    },
    
    // 风险严重程度
    getRiskSeverityType(severity) {
      const severityMap = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      };
      return severityMap[severity] || 'info';
    },
    
    // 查看详情
    viewInspectionDetails(inspection) {
      this.dialogTitle = '检验详情';
      this.detailData = inspection;
      this.currentDetailComponent = 'inspection-detail';
      this.dialogVisible = true;
    },
    viewDefectDetails(defect) {
      this.dialogTitle = '缺陷详情';
      this.detailData = defect;
      this.currentDetailComponent = 'defect-detail';
      this.dialogVisible = true;
    },
    viewBatchDetails(batch) {
      // 跳转到该批次的追溯页面
      this.$router.push({
        path: '/qep/data-analysis/trace',
        query: {
          type: 'batch',
          batchId: batch.id
        }
      });
    },
    
    // 导出批次记录
    exportData() {
      // 尝试从多个位置获取批次编号
      let batchNo = this.traceData?.batch?.batchNo;
      
      // 如果批次编号不存在，尝试从props获取
      if (!batchNo && this.batchNo) {
        batchNo = this.batchNo;
      }
      
      if (!batchNo) {
        this.$message.warning('无法获取批次编号，导出失败');
        return;
      }
      
      this.$message({
        message: '正在导出数据，请稍候...',
        type: 'info'
      });
      
      // 直接尝试导出，如果后端接口不存在会被捕获到catch中
      exportBatchTrace(batchNo).then(() => {
        this.$message.success('导出成功');
      }).catch(err => {
        console.error('导出失败:', err);
        this.$message.error('导出功能暂未实现，请联系管理员添加导出接口');
      });
    }
  }
}
</script>

<style scoped>
.batch-trace-result {
  margin-top: 20px;
}
.batch-card {
  margin-bottom: 20px;
}
.stats-row, .process-row, .inspection-row, .defect-row, .impact-row {
  margin-top: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.stats-item {
  text-align: center;
  padding: 15px 0;
}
.item-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.item-value {
  font-size: 28px;
  font-weight: bold;
}
.item-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
.chart-container {
  height: 300px;
  margin-top: 20px;
}
.text-excellent {
  color: #67c23a;
}
.text-good {
  color: #409EFF;
}
.text-adequate {
  color: #E6A23C;
}
.text-poor {
  color: #F56C6C;
}
.empty-data {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
</style> 